<? if ($c = stack('name')) {
	
	if (param('file') == 'list') {

//select a.document_id, ai.DESCRIPTION, ai.ATTACHDATE, ai.FILENAME, ac.content, ac.id
//from cc_attach a, cc_attachinfo ai, cc_attachcontent ac
//where ai.id = a.attachinfo_id and ac.id = a.attachcontent_id and a.document_id = gccHuuid(param('document'));

//		dbdebug();
		$files = datafetch_array('db_list', array(
			'table' => 'cc_attach a, cc_attachinfo ai, cc_attachcontent ac',
			'select' => 'a.document_id, ai.DESCRIPTION, ai.ATTACHDATE, ai.FILENAME, ac.content, a.id',
			'where' => 'ai.id = a.attachinfo_id and ac.id = a.attachcontent_id and a.document_id = ' . gccHuuid(param('document'))
		));

		foreach ($files as $id => $v) {
			$files[$id]['attachdate'] = date2str(parse_date($v['attachdate']), 'uk');
		}

		print json_encode($files);
		exit;


	} else {
		$id = gccHuuid(param('file'));

//		dbdebug();
//		$file = datafetch('db_item',
//			'cc_attach a
//			inner join cc_attachinfo ai on (ai.id=a.attachinfo_id)
//			inner join cc_attachcontent ac on (ac.id= a.attachcontent_id)',
//			'a.id = ' . $id,
//			'a.document_id, ai.DESCRIPTION, ai.ATTACHDATE, ai.filename, ac.content, a.id'
//		);

		$file = gccGetFile($id);
//		debug($file);
		header("Content-type: application/octet-stream\n");
		header('Content-Disposition: attachment; filename="'.trim($file['filename'])."\"\n");
		header('Content-Length: ' . strlen( $file['data'] )."\n");

		print $file['data'];
//		$file['content'] = strlen( $file['content'] );
//		debug($file);

		exit;
	}

unstack();
}